// Handle combo
App.directive('edCombo', ['$parse', '$timeout', 'w5cValidator', 'Page', function ($parse, $timeout, w5cValidator, Page) {

    return {

        restrict: 'A',

        replace: true,

        transclude: true,

        require: '^?form',

        template: function (elem, attrs) {

            var option = AppUtil.jsonfy(attrs.options);

            var id = attrs.edCombo || 'combo_' + Metronic.getUniqueID();
            var name = $(elem).parent().attr('name'), required = $(elem).parent().attr('required');

            return '<div id="' + id + '" class="form-control select2-container input-icon" data-options="' + (attrs.options || '') + '">'
                    +'<i class="fa fa-align-left"></i>'
                + '<input type="text" class="form-control" ' + (option.disabled ? 'disabled=true' : '' ) + (name ? 'name="' + name + '"' : '') + ' ng-model="' + id + '.searchName" ng-change="search()" placeholder="' + (option.placeholder || '') + '" ' + (required || '') + ' ng-click="' + id + '.show()">'
                + '<span class="select2-arrow" ' + (option.disabled ? '' : 'ng-click="' + id + '.show()"' ) + '><i class="fa fa-angle-down"></i></span>'
                + '<div class="select2-drop-active"' + (option.panelWidth ? ('style="width: ' + option.panelWidth + 'px;"') : '') + ' ng-show="' + id + '.showing"></div>'
                +'</div>';
        },

        link: function (scope, elem, attrs, controller, transcludeFn) {

            var drop = elem.find('.select2-drop-active'), input = $(elem).find('input:eq(0)');
            var isRequired = typeof(input.attr("required")) != 'undefined', validInput = (isRequired && controller) ? controller[input.attr('name')] : null;// 验证的表单元素

            transcludeFn(scope, function(cElement) {
                drop.append(cElement);
            });

            var id = $(elem).attr('id');
            var combo = scope[id] = {};
            combo.id = id;
            combo.showing = false;

            combo.show = function() {
                combo.showing = true;
                // 设置是上面显示还是下面显示
                var top = elem.offset().top - $(document).scrollTop();
                if ($(window).height() - top - elem.height() < 100) {
                    drop.css('bottom', (elem.height() - 1) + 'px');
                } else {
                    drop.css('bottom', 'initial');
                }
                $("body").bind("mousedown", onBodyDown);
                if (isRequired && validInput) {
                    w5cValidator.removeError(input);
                }
                return combo;
            }
            combo.hide = function() {
                combo.showing = false;
                $("body").unbind("mousedown", onBodyDown);
                // 表单校验
                if (isRequired && validInput) {
                    $timeout(function () {
                        if (!validInput.$valid) {
                            var errorMessages = w5cValidator.getErrorMessages(input, validInput.$error);
                            w5cValidator.showError(input, errorMessages);
                        } else {
                            w5cValidator.removeError(input);
                        }
                    }, 50);
                }
                return combo;
            }
            function onBodyDown(event) {
                var showHide = true;
                $($(event.target).parents('.select2-container')).each(function(i, ele) {
                    if ($(ele).attr('id') == id) {
                        showHide = false;
                        return false;
                    }
                });
                if (showHide) {
                    scope.$apply(function(){
                        combo.hide();
                        // 设置为上次选择的值
                        combo.searchName = combo.valueText || '';
                        if (scope.search) {
                            scope.search();
                        }
                    });
                }
            }
            combo.setText = function(text) {
                //input.val(text);
                combo.searchName = text;
                combo.valueText = text;
                if (scope.search) {
                    scope.search();
                }
                return combo;
            }
        }

    };
}]);